package com.kevin.pay.interceptor;

import com.google.gson.Gson;
import com.kevin.pay.domain.JsonData;
import com.kevin.pay.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {

    private static final Gson gson=new Gson();

    /**
     * 进入controller之前进行拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken=request.getHeader("token");
        if (accessToken==null){
            accessToken=request.getParameter("token");
        }
        if (accessToken!=null){
            Claims claims= JwtUtils.checkJWT(accessToken);
            Integer id= (Integer) claims.get("id");
            String name= (String) claims.get("name");
            request.setAttribute("user_id",id);
            request.setAttribute("name",name);
            return true;
        }
        sendJsonMessage(response, JsonData.buildError("请登录"));
        return false;
    }

    /**
     * 响应数据给前端
     * @param response
     * @param obj
     * @throws IOException
     */
    private void sendJsonMessage(HttpServletResponse response, Object obj) throws IOException {

        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer=response.getWriter();
        writer.print(gson.toJson(obj));
        writer.close();

        response.flushBuffer();
    }
}
